package com.ppp.poi.common;

import static com.ppp.poi.common.AppConstant.LOG_SPLIT;

import com.alibaba.fastjson.JSONObject;
import com.ppp.poi.bean.base.AppResult;
import com.ppp.poi.bean.enumeration.RES_STATUS;
import com.ppp.poi.common.exception.AppException;
import com.ppp.poi.common.exception.AppSimpleException;
import com.ppp.poi.common.utils.RequestUtil;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * @author Wu Jin
 * @create 2020-01-19
 */
@RestControllerAdvice
@Slf4j
public class AppExceptionHandler {


  @ExceptionHandler(AppSimpleException.class)
  public AppResult<Void> handlerAppSimpleException(AppSimpleException e,
      HttpServletRequest request, HttpServletResponse response) {
    AppResult<Void> result = new AppResult<Void>();
    result.setCode(e.getCode());
    result.setMsg(e.getMsg());
    log.error(
        request.getRequestURI() + LOG_SPLIT + RequestUtil.getIp(request)
            + LOG_SPLIT + JSONObject.toJSONString(result) + LOG_SPLIT
            + result.getCode() + LOG_SPLIT
            + JSONObject.toJSONString(RequestUtil.getHttpParameter(request))
            + LOG_SPLIT + request.getMethod());
    return result;
  }

  @ExceptionHandler(AppException.class)
  public AppResult<Void> handlerAppException(AppException e,
      HttpServletRequest request, HttpServletResponse response) {
    AppResult<Void> result = new AppResult<Void>();
    result.setCode(e.getCode());
    result.setMsg(e.getMsg());
    log.error(
        request.getRequestURI() + LOG_SPLIT + RequestUtil.getIp(request)
            + LOG_SPLIT + JSONObject.toJSONString(result) + LOG_SPLIT
            + result.getCode() + LOG_SPLIT
            + JSONObject.toJSONString(RequestUtil.getHttpParameter(request))
            + LOG_SPLIT + request.getMethod(), e);
    return result;
  }

  @ExceptionHandler(Exception.class)
  public AppResult<Void> handlerException(Exception e,
      HttpServletRequest request, HttpServletResponse response) {
    AppResult<Void> result = new AppResult<Void>();
    result.setCode(RES_STATUS.SERVER_UNKONW_ERROR.code);
    result.setMsg(e.getMessage());
    log.error(
        request.getRequestURI() + LOG_SPLIT + RequestUtil.getIp(request)
            + LOG_SPLIT + JSONObject.toJSONString(result) + LOG_SPLIT
            + result.getCode() + LOG_SPLIT
            + JSONObject.toJSONString(RequestUtil.getHttpParameter(request))
            + LOG_SPLIT + request.getMethod(), e);
    return result;
  }


}
